<?php

class ControllerAccountAccount extends Controller
{
    private $error = array();

    public function register(){
        if (! $this->actionCheck(false, true)) {
            return;
        }
    }


    public function edit()
    {
        $this->load->model('account/customer');

        if (! $this->actionCheck(true, true)) {
            return;
        }
        if ($this->validate()) {
            $this->model_account_customer->editCustomerByKeyValue($this->request->post['key'], $this->request->post['value']);
            $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
            $this->load->model('tool/easemob');

            if ($this->request->post['key'] == 'password') {
                $this->model_tool_easemob->setPassword('cook' . $this->customer->getId(), md5($customer_info['password']));
            } else
                if ($this->request->post['key'] == 'nickname') {
                    $this->model_tool_easemob->setNickname('cook' . $this->customer->getId(), $this->request->post['nickname']);
                }
            $this->response->setDataResult(1, "", null);
        } else {
            if (count($this->error) > 0) {
                $error_warning = array_shift($this->error);
            } else {
                $error_warning = '';
            }
            $this->response->setDataResult(0, $error_warning, null);
            return;
        }
    }

    public function editCustomerInfo()
    {
        $this->load->model('account/customer');
        $this->load->model('account/reward');
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $step = $this->request->post['step'];
        // 用户信息第一步（完善信息（家长姓名、家长电话、孩子年级、所在省市地区）可获得10积 分）
        if ($step == 1) {
            if ($this->CustomerInfoOneValidate()) {
                $this->model_account_customer->editCustomerInfo($this->request->post,$step);
                $this->model_account_reward->addReward($this->customer->getId(),"用户完善信息第一步,获得10积分",10);

                $this->response->setDataResult(1, '成功', null);
            } else {
                if (count($this->error) > 0) {
                    $error_warning = array_shift($this->error);
                } else {
                    $error_warning = '';
                }
                $this->response->setDataResult(0, $error_warning, null);
                return;
            }
        }
        // 用户信息第二步(继续完善信息（购买时间、机身编码）可再获得20积分)
        else if ($step == 2) {
                if ($this->CustomerInfoTwoValidate()) {
                $this->model_account_customer->editCustomerInfo($this->request->post,$step);
                $this->model_account_reward->addReward($this->customer->getId(),"用户完善信息第二步,获得20积分",20);
                $this->response->setDataResult(1, '成功', null);
                } else {
                    if (count($this->error) > 0) {
                        $error_warning = array_shift($this->error);
                    } else {
                        $error_warning = '';
                    }
                    $this->response->setDataResult(0, $error_warning, null);
                    return;
                }
            }
            // 用户信息第三步(再继续完善信息（推荐人手机号）可再次获得10积分)
            else {


            }
    }

    //获取登录用户的推荐人
    public function getRecommendUser(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/customer');
        $data =  $this->model_account_customer->getRecommendUser();
        $this->response->setDataResult(1, '成功', $data);
    }

    //编辑家长信息
    public function editParent(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $this->model_account_customer->updateParent($this->request->post);
        $this->response->setDataResult(1, '成功', null);

    }

    //添加推荐人信息
    public function AddRecommend(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $this->model_account_customer->AddRecommend($this->request->post);
        $this->response->setDataResult(1, '成功', null);
    }

    //改变推荐人信息
    public function modifyRecommend(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $this->model_account_customer->modifyRecommend($this->request->post);
        $this->response->setDataResult(1, '成功', null);
    }

    //新增孩子
    public function addChild(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer_child');

        $this->response->setDataResult(1, '成功', null);
    }

    //定义孩子
    public function modifyChild(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer_child');
        $child = $this->model_account_customer_child->getChildBySort($this->request->post['sort']);
        if($child){
            $this->model_account_customer_child->updateChild($this->request->post);
            $this->response->setDataResult(1, '修改孩子成功', null);
        }else{
            $this->model_account_customer_child->addChild($this->request->post);
            $this->response->setDataResult(1, '新增孩子成功', null);
        }
    }


    //获取用户绑定的孩子
    public function getCustomerChilds(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/customer_child');
        $data =  $this->model_account_customer_child->getCustomerChilds();
        $this->response->setDataResult(1, '成功', $data);
    }

    //根据Sort获取孩子
    public function getChildBySort(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/customer_child');
        $data =  $this->model_account_customer_child->getChildBySort($this->request->get['sort']);
        $this->response->setDataResult(1, '成功', $data);
    }


    //注册后编辑信息第一步
    public function editCustomerInfoOne(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $this->load->model('account/customer_child');
        $this->model_account_customer_child->addChild($this->request->post);
        $this->model_account_customer->updateParent($this->request->post);
        $this->model_account_customer->addCustomerHardWare($this->request->post);
        $this->response->setDataResult(1, '成功', null);
    }
    //注册后编辑信息第二步
    public function editCustomerInfoTwo(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $this->model_account_customer->AddRecommend($this->request->post);
        $this->response->setDataResult(1, '成功', null);
    }

    public function wxregisterbind()
    {
        $this->load->model('account/customer');

        if (! $this->actionCheck(false, true)) {
            return;
        }

        if ($this->registerValidate()) {
            $this->model_account_customer->addCustomer($this->request->post);

            unset($this->session->data['phone_valide_code']);

            // Clear any previous login attempts for unregistered accounts.
            $this->model_account_customer->deleteLoginAttempts($this->request->post['telephone']);

            $this->customer->login($this->request->post['telephone'], $this->request->post['password']);

            unset($this->session->data['guest']);

            // Add to activity log
            $this->load->model('account/activity');

            $activity_data = array(
                'customer_id' => $this->customer->getId(),
                'name' => $this->request->post['firstname']
            );

            $this->model_account_activity->addActivity('register', $activity_data);

            $this->load->model('account/social');

            $this->model_account_social->addSocial($data = array(
                'uid' => $this->request->post['open_id'],
                'social_type' => 1,
                'customer_id' => $this->customer->getId()
            ));

            $this->response->setDataResult(1, "注册成功", null);
            return;
        }

        if (count($this->error) > 0) {
            $error_warning = array_shift($this->error);
        } else {
            $error_warning = '';
        }
        $this->response->setDataResult(0, $error_warning, null);
        return;
    }

    // 获取优惠券
    public function getcoupon()
    {
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('marketing/coupon');
        if ($this->model_marketing_coupon->coupon_Isoverdue($this->request->get['coupon_id'])) {
            $this->response->setDataResult(0, "优惠劵已过期！", null);
            return;
        }
        $coupon = $this->model_marketing_coupon->getCoupon($this->request->get['coupon_id']);
        if ($coupon) {
            if ($this->model_marketing_coupon->isgetCoupon($this->request->get['coupon_id'])) {
                $this->response->setDataResult(0, "你已领取过了此优惠券!", null);
                return;
            } else {
                $id = $this->model_marketing_coupon->addCustomerCoupon($this->request->get['coupon_id']);
                $customer_coupon = $this->model_marketing_coupon->getCoupon($id);
                $this->response->setDataResult(1, "领取成功!", $customer_coupon);
                return;
            }
        } else {
            $this->response->setDataResult(0, "优惠劵已被领取完！", null);
            return;
        }
    }




    // 用户优惠券
    public function customercoupon()
    {
        if (! $this->actionCheck(true, false)) {
            return;
        }

        $this->load->model('marketing/coupon');
        $query_datas = $this->model_marketing_coupon->getCustomerCoupons();
        $data['customer_coupons'] = array();
        foreach ($query_datas as $query_data) {
            $data['customer_coupons'][] = array(
                'customer_id' => $query_data['customer_id'],
                'is_use' => $query_data['is_use'],
                'num' => $query_data['num'],
                'coupon_id' => $query_data['coupon_id'],
                'name' => $query_data['name'],
                'code' => $query_data['code'],
                'type' => $query_data['type'],
                'discount' => $query_data['discount'],
                'logged' => $query_data['logged'],
                'shipping' => $query_data['shipping'],
                'total' => $query_data['total'],
                'date_start' => $query_data['date_start'],
                'date_end' => $query_data['date_end'],
                'uses_total' => $query_data['uses_total'],
                'status' => $query_data['status'],
                'date_added' => $query_data['date_added']
            );
        }

        $this->response->setDataResult(1, "", $data);
    }


    public function customerLotteryRecord(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/lottery');
        $query_datas = $this->model_account_lottery->getCustomerLotteryRecord();
        $this->response->setDataResult(1, "成功", $query_datas);
    }

    //用户获取绑定优学派硬件
    public function getCustomerHardWare(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/customer');
        $data = $this->model_account_customer->getCustomerHardWare($this->customer->getId());
        $this->response->setDataResult(1, '成功', $data);

    }


    //获取机型列表接口
    public function getProductCateInfo(){
        $url = "http://sales.noahedu.com/salestat/basicsDetail/getProductCateInfo";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res,true);
        if($result['msgCode']==302){
            $this->response->setDataResult(1, '成功', $result['data']);
        }else{
            $this->response->setDataResult(1, '成功', null);
        }
    }



    //获取网点接口
    public function getNetworkInfo(){
        $id = $this->request->get['areaid'];
        $url = "http://sales.noahedu.com/salestat/basicsDetail/getNetworkInfo?area_id=".$id;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res,true);
        if($result['msgCode']==302){
            $this->response->setDataResult(1, '成功', $result['data']);
        }else{
            $this->response->setDataResult(1, '成功', null);
        }
    }

    //获取优学派区域列表
    public  function getAreaInfo(){
        if (! $this->actionCheck(false, false)) {
            return;
        }
        $this->load->model('account/customer');
        $query_datas = $this->model_account_customer->getAreaInfo($this->request->get['id']);
        $this->response->setDataResult(1, "成功", $query_datas);
    }

    //保存优学派硬件
    public function saveHardWare(){
        if (! $this->actionCheck(true, true)) {
            return;
        }
        $this->load->model('account/customer');
        $data = $this->model_account_customer->addCustomerHardWare($this->request->post);

        $this->response->setDataResult(1, '成功', $data);

    }

    public function userProfile()
    {
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $this->load->model('account/activity');
        $activity_data = array(
            'customer_id' => $this->customer->getId(),
            'name' => $this->customer->getFirstName()
        );
        $this->model_account_activity->addActivity('userProfile', $activity_data);
        $data = $this->customer->getCustomerInfo();
        $this->response->setDataResult(1, "", $data);
    }



    protected function loginValidate()
    {
        if (! isset($this->request->post['telephone'])) {
            $this->error['warning'] = '请输入手机号码';
        } else
            if (! isset($this->request->post['password']) || utf8_strlen($this->request->post['password']) < 6) {
                $this->error['warning'] = '密码格式错误';
            }
        return ! $this->error;
    }

    protected function registerValidate()
    {
        if (isset($this->request->post['code'])) {
            if (! preg_match('/^\d{4}$/i', $this->request->post['code'])) {
                $this->error['code'] = '请输入4位数字短信验证码！';
            } else
                if (! isset($this->session->data['phone_valide_code'])) {
                    $this->error['code'] = '无效的短信验证码!'; // '无效的短信验证码！';
                } else
                    if ($this->session->data['phone_valide_code']!=$this->request->post['code']) {
                        $this->error['code'] = '短信验证码错误！';
                    }
        }

        if (! preg_match('/^1\d{10}$/', $this->request->post['telephone'])) {
            $this->error['phone'] = '手机号不合法！';
        }
        if ((utf8_strlen($this->request->post['password']) < 6) || (utf8_strlen($this->request->post['password']) > 20)) {
            $this->error['password'] = '请输入6-20位密码！';
        }
        if (! $this->error) {
            if ($this->model_account_customer->getTotalCustomersByPhone($this->request->post['telephone'])) {
                $this->error['warning'] = '手机号已注册！';
            }
        }

        return ! $this->error;
    }

    // 默认获取某优惠券
    protected function getDefaultCoupon($coupon_id)
    {
        $this->load->model('marketing/coupon');
        if ($this->model_marketing_coupon->coupon_Isoverdue($coupon_id)) {
            return;
        }
        $coupon = $this->model_marketing_coupon->getCoupon($coupon_id);
        if ($coupon) {
            if ($this->model_marketing_coupon->isgetCoupon($coupon_id)) {
                return;
            } else {
                $id = $this->model_marketing_coupon->addCustomerCoupon($coupon_id);
                return;
            }
        } else {
            return;
        }
    }

    protected function CustomerInfoOneValidate()
    {
        if (empty($this->request->post['lastname'])) {
            $this->error['lastname'] = '请填写家长姓名！';
        }
        if (! preg_match('/^1\d{10}$/', $this->request->post['telephone'])) {
            $this->error['telephone'] = '手机号不合法！';
        }
        if (empty($this->request->post['birthday'])) {
            $this->error['lastname'] = '请填写出生日期！';
        }
        if (empty($this->request->post['grade_time'])) {
            $this->error['lastname'] = '请填写出生日期！';
        }
        if ($this->request->post['country_id'] == 0 || $this->request->post['zone_id'] == 0) {
            $this->error['address'] = '请填写地址';
        }

        return ! $this->error;
    }

    protected function CustomerInfoTwoValidate(){
        if (empty($this->request->post['buy_time'])) {
            $this->error['buy_time'] = '请填写购买时间';
        }
        if (empty($this->request->post['hardware_code'])) {
            $this->error['hardware_code'] = '请填写优学派机身编码';
        }

        return ! $this->error;
    }


    public function getUnReadCount(){
        if (! $this->actionCheck(true, false)) {
            return;
        }
        $customer_question_count =(int)$this->db->query("select count(*) total from customer_question where customer_id = '".(int)$this->customer->getId()."'")->row['total'];
        $question_count = (int)$this->db->query("select count(*) total from question where customer_id = '".(int)$this->customer->getId()."'")->row['total'];
        $data['question_count'] = $question_count - $customer_question_count;
        $data['activity_count'] = (int)$this->db->query("select count(*) total from customer_activity_article where customer_id = '".(int)$this->customer->getId()."' and `read`  = 0 ")->row['total'];
        $customer_subscription_count =(int)$this->db->query("select count(*) total from customer_subscription where customer_id = '".(int)$this->customer->getId()."'")->row['total'];
        $subscription_count = (int)$this->db->query("SELECT
	COUNT(b.ID) total
FROM
	(
		(
			SELECT DISTINCT
				a.ID
			FROM
				wp_posts a
			JOIN wp_term_relationships b ON a.ID = b.object_id
			JOIN wp_term_taxonomy c ON b.term_taxonomy_id = c.term_taxonomy_id
			JOIN customer_wpcategory d ON c.term_id = d.category_id
			WHERE
				d.customer_id = '".(int)$this->customer->getId()."'
		)
		UNION
			(
				SELECT
					b.ID
				FROM
					customer_article a
				JOIN wp_posts b ON a.post_id = b.ID
				WHERE
					a.customer_id = '".(int)$this->customer->getId()."'
				AND a.avail_time < CURRENT_TIMESTAMP
			)
	) AS a
JOIN wp_posts b ON a.ID = b.ID")->row['total'];
        $data['subscription_count'] = $subscription_count - $customer_subscription_count;
        $this->response->setDataResult(1, '成功', $data);

    }

}